#!/usr/bin/env python

import webapp2
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import ndb
import datetime
from google.appengine.ext.ndb import Key



class Event(ndb.Model):   
    author = ndb.UserProperty()
    description = ndb.StringProperty()
    date = ndb.DateTimeProperty(auto_now_add = True)
    eventdate = ndb.DateTimeProperty(auto_now_add = True)
    title = ndb.StringProperty()
    #location = ndb.GeoPtProperty();
    #keywords = ndb.StringListProperty()



class MainHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = ("Logged in as %s - <a href=\"%s\">sign out</a>" %
                        (user.nickname(), users.create_logout_url("/")))
        else:
            greeting = ("<a href=\"%s\">Sign in or register</a>." %
                        users.create_login_url("/"))
        events = ndb.gql("SELECT * FROM Event ORDER BY date, title DESC")
        #self.response.out.write(template.render('main.html', {'greeting':greeting, 'events':events}))
        self.response.write(template.render('main.html', {'greeting':greeting, 'events':events}))

    def post(self):
        if users.get_current_user():
            event = Event()
            event.author = users.get_current_user()
            event.description = self.request.get('description')
            event.eventdate = datetime.datetime.strptime(self.request.get('eventdate'), "%d/%m/%Y")
            event.title = self.request.get('title')
            #event.location = self.request.get('location')
            event.put()
               
            #events = ndb.gql("SELECT * FROM Event ORDER BY date, title DESC", "")
            
        self.redirect('/')

class deleteEvent(webapp2.RequestHandler):
    def post(self):
        if users.get_current_user():
            eventtodelete=self.request.get('eventtodelete')
            if eventtodelete != "":               
                event = Key(urlsafe=eventtodelete).get()
                if event != None and event.author == users.get_current_user():
                    event.key.delete()    
        self.redirect('/')
        

app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/delete', deleteEvent)],
                               debug=True)
    
